const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const auth = require('../middleware/auth');
const PlanetSchema = require('../models/Planet');
const User = require('../models/User');

// 创建Planet模型
const Planet = mongoose.model('Planet', PlanetSchema);

/**
 * @route GET /api/planets/:userId
 * @desc 获取特定用户的星球数据
 * @access Private
 */
router.get('/:userId', auth, async (req, res) => {
  try {
    // 验证访问权限（只能访问自己的数据或管理员可以访问所有）
    if (req.params.userId !== req.user.id && !req.user.isAdmin) {
      return res.status(403).json({ msg: '无权访问此数据' });
    }
    
    // 查找用户星球数据
    const planet = await Planet.findOne({ userId: req.params.userId });
    
    if (!planet) {
      return res.status(404).json({ msg: '未找到星球数据' });
    }
    
    res.json(planet);
  } catch (err) {
    console.error('获取星球数据错误:', err.message);
    res.status(500).send('服务器错误');
  }
});

/**
 * @route POST /api/planets
 * @desc 创建新的星球数据
 * @access Private
 */
router.post('/', auth, async (req, res) => {
  try {
    // 检查是否已存在该用户的星球数据
    let planet = await Planet.findOne({ userId: req.user.id });
    
    if (planet) {
      return res.status(400).json({ msg: '用户已有星球数据' });
    }
    
    // 创建新的星球数据
    planet = new Planet({
      userId: req.user.id,
      activeLandmarks: req.body.activeLandmarks || [],
      achievements: req.body.achievements || [],
      ecoTasks: req.body.ecoTasks || [],
      challengeTasks: req.body.challengeTasks || [],
      completedTasksHistory: req.body.completedTasksHistory || [],
      lastUpdated: new Date()
    });
    
    await planet.save();
    
    res.json(planet);
  } catch (err) {
    console.error('创建星球数据错误:', err.message);
    res.status(500).send('服务器错误');
  }
});

/**
 * @route PUT /api/planets/:userId
 * @desc 更新星球数据
 * @access Private
 */
router.put('/:userId', auth, async (req, res) => {
  try {
    // 验证访问权限
    if (req.params.userId !== req.user.id && !req.user.isAdmin) {
      return res.status(403).json({ msg: '无权更新此数据' });
    }
    
    // 查找星球数据
    let planet = await Planet.findOne({ userId: req.params.userId });
    
    // 如果不存在，创建新记录
    if (!planet) {
      planet = new Planet({
        userId: req.params.userId,
        activeLandmarks: [],
        achievements: [],
        ecoTasks: [],
        challengeTasks: [],
        completedTasksHistory: []
      });
    }
    
    // 更新数据
    planet.activeLandmarks = req.body.activeLandmarks || planet.activeLandmarks;
    planet.achievements = req.body.achievements || planet.achievements;
    planet.ecoTasks = req.body.ecoTasks || planet.ecoTasks;
    planet.challengeTasks = req.body.challengeTasks || planet.challengeTasks;
    planet.completedTasksHistory = req.body.completedTasksHistory || planet.completedTasksHistory;
    planet.lastUpdated = new Date();
    
    await planet.save();
    
    res.json(planet);
  } catch (err) {
    console.error('更新星球数据错误:', err.message);
    res.status(500).send('服务器错误');
  }
});

/**
 * @route GET /api/planets/statistics
 * @desc 获取所有用户的星球统计数据
 * @access Admin
 */
router.get('/statistics', auth, async (req, res) => {
  try {
    // 验证管理员权限
    if (!req.user.isAdmin) {
      return res.status(403).json({ msg: '需要管理员权限' });
    }
    
    // 获取统计数据
    const planets = await Planet.find().select('-ecoTasks -challengeTasks');
    
    // 计算统计信息
    const statistics = {
      totalPlanets: planets.length,
      totalLandmarks: 0,
      totalAchievements: 0,
      userDistribution: []
    };
    
    const users = await User.find({ _id: { $in: planets.map(p => p.userId) } })
      .select('username');
    
    const userMap = {};
    users.forEach(user => {
      userMap[user._id] = user.username;
    });
    
    planets.forEach(planet => {
      statistics.totalLandmarks += planet.activeLandmarks.length;
      statistics.totalAchievements += planet.achievements.filter(a => a.unlocked).length;
      
      statistics.userDistribution.push({
        userId: planet.userId,
        username: userMap[planet.userId] || '未知用户',
        landmarks: planet.activeLandmarks.length,
        achievements: planet.achievements.filter(a => a.unlocked).length,
        lastUpdated: planet.lastUpdated
      });
    });
    
    res.json(statistics);
  } catch (err) {
    console.error('获取星球统计数据错误:', err.message);
    res.status(500).send('服务器错误');
  }
});

module.exports = router; 